package servlets;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import beans.Usuario;
import beans.dao.UsuarioDAO;


public class CadastroUsuarioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public CadastroUsuarioServlet() {
        super();
    }

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		processaCadastro(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaCadastro(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void processaCadastro(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
		request.setCharacterEncoding("UTF-8");					
		
		//HIBERNATE
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");		
		boolean administrador;
		if(request.getParameter("administrador") != null
				&& request.getParameter("administrador").equals("true"))
			administrador = true;
		else
			administrador = false;	
		
		String url = "";
		
		UsuarioDAO DAO = new UsuarioDAO();		
		DAO.beginTransaction();
		Usuario u = DAO.retrieve(email);
		if(u == null){
			u = new Usuario();
			u.setEmail(email);
			u.setSenha(senha);
			u.setAdministrador(administrador);
			u.setAtivo(true);
			DAO.insert(u);
			
			url = "login.jsp"; 
			
		} else{
			JOptionPane.showMessageDialog(null,"Email já cadastrado!" );
			url = "cadastrousuario.jsp"; 	
		}
		DAO.commit();
		
		
		
		response.setContentType("text/html;charset=UTF-8");  
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

}
